﻿/**
 * Copyright (C) 2012 original author and authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NGuice.Inject.Internal.Util;

namespace NGuice.Inject.Internal
{
    //complete!
    internal sealed class InternalFactoryToProviderAdapter<T> : InternalFactory<T>
    {
        private readonly Initializable<IProvider<T>> initializable;
        private readonly object source;

        public InternalFactoryToProviderAdapter(Initializable<IProvider<T>> initializable, object source)
        {
            this.initializable = Preconditions.CheckNotNull(initializable, "provider");
            this.source = Preconditions.CheckNotNull(source, "source");
        }

        /// <summary>
        /// 出现异常则抛出ErrorsException
        /// </summary>
        public T Get(Errors errors, InternalContext context, Spi.Dependency dependency, bool linked)
        {
            try
            {
                return errors.CheckForNull(initializable.Get(errors).Get(), source, dependency);
            }
            catch (Exception e)
            {
                throw errors.WithSource(source).ErrorInProvider(e).ToException();
            }
        }

        object InternalFactory.Get(Errors errors, InternalContext context, Spi.Dependency dependency, bool linked)
        {
            return Get(errors, context, dependency, linked);
        }

        public override string ToString()
        {
            return initializable.ToString();
        }
       
    }
}
